package controller;

import model.Student;
import net.sf.json.JSONObject;
import service.AjaxService;
import service.impl.AjaxServiceImpl;
import util.DBUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/Educational/student/ajax")
public class AjaxServlet extends HttpServlet {
    AjaxService ajaxService = new AjaxServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("getByStuNo".equals(method)) {
            getByStuNo(req, resp);
        } else if ("getByStuName".equals(method)) {
            getByStuName(req, resp);
        } else if ("getByStuIdNumber".equals(method)) {
            getByStuIdNumber(req, resp);
        }
    }

    protected void getByStuNo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String stuno = req.getParameter("stuno");
        Student studentByStuNo = ajaxService.getStudentByStuNo(stuno);
        JSONObject jsonObject = JSONObject.fromObject(studentByStuNo);
        PrintWriter writer = resp.getWriter();
        writer.print(jsonObject);
    }

    protected void getByStuName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String stuname = req.getParameter("stuname");
        Student studentByStuNo = ajaxService.getStudentByStuName(stuname);
        JSONObject jsonObject = JSONObject.fromObject(studentByStuNo);
        PrintWriter writer = resp.getWriter();
        writer.print(jsonObject);
    }

    protected void getByStuIdNumber(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String stuidnumber = req.getParameter("stuidnumber");
        Student studentByStuNo = ajaxService.getStudentByStuIdNumber(stuidnumber);
        JSONObject jsonObject = JSONObject.fromObject(studentByStuNo);
        PrintWriter writer = resp.getWriter();
        writer.print(jsonObject);
    }
}
